<?php
/**
 * Created by PhpStorm.
 * User: yys
 * Date: 2017/1/10
 * Time: 22:42
 * 采购订单后台
 */

namespace App\Services\PurchaseOrderService;


use App\Services\BrandService\BrandToolService;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\SupplierService\SupplierTool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
class PurchaseOrderBackService
{
    private $productTempTool;
    /**
     * PurchaseOrderBackService constructor.
     */
    public function __construct(ProductTempTool $productTempTool)
    {
        $this->productTempTool=$productTempTool;
    }

    /***
     * 保存订货单
     * @param array $data
     * @return bool
     */
    function save(array $data){
        try{
            $product_temp_skus=$data['product_temp_skus'];
            $supplier_id=$data['supplier_id'];
            $purchase_order['remark']=$data['remark'];
            $purchase_order['supplier_id']=$supplier_id;
            $purchase_order['actual_fee']=$data['actual_fee'];
            $purchase_order['postage']=$data['postage'];
            $purchase_order['order_express_id']=$data['order_express_id'];
            $purchase_order['express_id']=$data['express_id'];
            $supplier_name=SupplierTool::getNameBySupplierID($supplier_id);
            $purchase_order['supplier_name']=empty($supplier_name)?'':$supplier_name;
            $purchase_order_id=$this->savePurchaseOrderToDB($purchase_order);
            if($purchase_order_id==false){
                return false;
            }
            foreach ($product_temp_skus as $product_temp_sku){
                $temp_sku_arr=explode('_',$product_temp_sku);
                $sku=$temp_sku_arr[0];
                $price=$temp_sku_arr[1];
                $num=$temp_sku_arr[2];
                $actual_fee=$temp_sku_arr[3];
                $purchase_order_detail=array();
                $purchase_order_detail['purchase_order_id']=$purchase_order_id;
                $purchase_order_detail['sku']=$sku;
                $purchase_order_detail['price']=$price;
                $purchase_order_detail['num']=$num;
                $purchase_order_detail['total_fee']=$actual_fee;
                $purchase_order_detail['actual_fee']=$actual_fee;
                $product_temp_stock=$this->productTempTool->getProductTempStockBySku($sku);
                if(empty($product_temp_stock)){
                    continue;
                }
                $purchase_order_detail['product_temp_id']=$product_temp_stock->product_temp_id;
                $purchase_order_detail['colour_id']=$product_temp_stock->colour_id;
                $purchase_order_detail['colour_name']=$product_temp_stock->colour_name;
                $purchase_order_detail['size_name']=$product_temp_stock->size_name;
                $this->savePurchaseOrderDetailToDB($purchase_order_detail);
            }
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 保存采购单主表主要信息
     * @param array $purchase_order
     * @return bool
     */
    private function savePurchaseOrderToDB(array  $purchase_order){
        try{
            $time=time();
            $purchase_order['state']=1;
            $purchase_order['created_at']=$time;
            $purchase_order['updated_at']=$time;
            $id=DB::table('purchase_orders')->insertGetId($purchase_order);
            return $id;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 更新采购单主表主要信息
     * @param array $purchase_order
     * @return bool
     */
    public function updatePurchaseOrderToDB(array  $purchase_order){
        try{
            $purchase_order_id=$purchase_order['purchase_order_id'];
            $time=time();
            $purchase_order['updated_at']=$time;
            $num=DB::table('purchase_orders')->where(array(
                'purchase_order_id'=>$purchase_order_id
            ))->update($purchase_order);
            return ($num>=1)?true:false;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 更新实际库存数
     * @param $sku
     * @param $add_stock
     * @return bool|int
     */
    public function updateTempActualStock($sku,$add_stock){
        try{
            //当前实际库存数
            $old_actual_stock=ProductTempTool::getActualStockBySku($sku);
            $actual_stock=$old_actual_stock+$add_stock;
            $update_res=$this->productTempTool->updateProdTempActualStockBySKuInDB($sku,$actual_stock);
            return $update_res;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    /***
     * 判断采购单是不是存在
     * @param $id
     * @return bool
     */
    public function purchaseOrderExistById($id){
        $num=DB::table('purchase_orders')->where(array('purchase_order_id'=>$id,'state'=>1))->count();
        return ($num<1)?false:true;
    }

    /***
     * 判断订货单下的sku是不是存在
     * @param $purchase_order_id
     * @param $sku
     * @return bool
     */
    public function purchaseOrderDetailExistByPurchaseOrderIdAndSku($purchase_order_id,$sku,$state=1){
        if(empty($purchase_order_id)||empty($sku)){
            return false;
        }
        $query=DB::table('purchase_order_details')
            ->where(array(
                'purchase_order_id'=>$purchase_order_id,
                'sku'=>$sku));
        if($state==1){
            $query->where('state',$state);
        }
        $num=$query->count();
        return ($num<1)?false:true;
    }
    /***
     * id獲取订货单主要信息
     * @param $id
     * @return null
     */
    public function getPurchaseOrderById($id){
        if(empty($id)||!is_int($id)){
            return null;
        }
        $purchase_order=DB::table('purchase_orders')
            ->where(array(
                'purchase_order_id'=>$id,
                'state'=>1
            ))->first();
        return $purchase_order;
    }
    /***
     * 获取订货单Id订货明细
     * @param $purchase_order_id
     * @return array
     */
    public function getPurchaseOrderDetailByPurchaseOrderId($purchase_order_id){
        if(empty($purchase_order_id)||!is_int($purchase_order_id)){
            return array();
        }
        $purchase_order_details=DB::table('purchase_order_details')
            ->where(array(
                'purchase_order_id'=>$purchase_order_id,
                'state'=>1
            ))->get()
            ->toArray();
        return empty($purchase_order_details)?array():$purchase_order_details;
    }
    /***
     * 保存采购明细主要信息
     * @param array $purchase_order_detail
     * @return bool
     */
    private function savePurchaseOrderDetailToDB(array  $purchase_order_detail){
        try{
            $time=time();
            $purchase_order_detail['state']=1;
            $purchase_order_detail['created_at']=$time;
            $purchase_order_detail['updated_at']=$time;
            $id=DB::table('purchase_order_details')->insertGetId($purchase_order_detail);
            return $id;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 更新采购明细主要信息
     * @param array $purchase_order_detail
     * @return bool
     */
    private function updatePurchaseOrderDetailToDB(array  $purchase_order_detail){
        try{
            $purchase_order_id=isset($purchase_order_detail['purchase_order_id'])?$purchase_order_detail['purchase_order_id']:0;
            $sku=isset($purchase_order_detail['sku'])?$purchase_order_detail['sku']:'';
            $id=isset($purchase_order_detail['id'])?$purchase_order_detail['id']:0;
            if(!empty($purchase_order_id)&&!empty($sku)){
                $query=DB::table('purchase_order_details')->where(array(
                    'purchase_order_id'=>$purchase_order_id,
                    'sku'=>$sku,
                ));
            }elseif (!empty($id)){
                $query=DB::table('purchase_order_details')->where(array(
                    'id'=>$id,
                ));
            }
            if(!isset($query)){
                return false;
            }
            $time=time();
            $purchase_order_detail['updated_at']=$time;
            $num=$query->update($purchase_order_detail);
            return ($num>=1)?true:false;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 删除订货单Id下的订货明细
     * @param $purchase_order_id
     * @return bool
     */
    public function delPurchaseOrderDetailByPurchaseOrderId($purchase_order_id){
        try{
            $num=DB::table('purchase_order_details')->where(array(
                'purchase_order_id'=>$purchase_order_id,
                'state'=>1
            ))->update(array(
                'state'=>0,
                'updated_at'=>time()
            ));
            return ($num>=1)?true:false;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 删除订货单绑定下的sku
     * @param $purchase_order_id
     * @param $sku
     * @return bool
     */
    public function delPurchaseOrderDetailByPurchaseOrderIdAndSku($purchase_order_id,$sku){
        try{
            $num=DB::table('purchase_order_details')->where(array(
                'purchase_order_id'=>$purchase_order_id,
                'sku'=>$sku,
                'state'=>1
            ))->update(array(
                'state'=>0,
                'updated_at'=>time()
            ));
            return ($num>=1)?true:false;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 添加订货单明细
     * @param array $purchase_order_detail
     * @return bool
     */
    public function addPurchaseOrderDetail(array $purchase_order_detail){
        try{
            $purchase_order_id=$purchase_order_detail['purchase_order_id'];
            $sku=$purchase_order_detail['sku'];
            $order_detail_exist=$this->purchaseOrderDetailExistByPurchaseOrderIdAndSku($purchase_order_id,$sku,0);
            if($order_detail_exist){
                $purchase_order_detail['state']=1;
                $res=$this->updatePurchaseOrderDetailToDB($purchase_order_detail);
            }else{
                $res=$this->savePurchaseOrderDetailToDB($purchase_order_detail);
            }
            return $res;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    /***
     * 分页获取采购单主要信息
     * @return mixed
     */
    public function getPurchaseOrderList(array  $data){
      try{
          $status=$data['status'];
          $supplier_id=$data['supplier_id'];
          $query= DB::table('purchase_orders')->where('state',1);
          if(!empty($status)){
              $query->where('purchase_order_status',$status);
          }
          if(!empty($supplier_id)){
              $query->where('supplier_id',$supplier_id);
          }
          $query->orderby('updated_at','DESC');
          $purchase_orders=$query->paginate(10);
          $purchase_orders->appends(['status' => $status,'supplier_id' => $supplier_id])
              ->render();
          return $purchase_orders;
      }catch (\Exception $e){
          Log::info($e);
          return false;
      }
    }

    /***
     * 导出供应商可提供的产品模板 Execl
     * @param array $product_temp_ids
     * @return bool|string
     */
    public function exportExcelByProductTempIds(array $product_temp_ids){
      try{
          if(empty($product_temp_ids)){
              return false;
          }
          $product_temps=$this->productTempTool->getProductTempStocksWhereInProductTemps($product_temp_ids);
          foreach($product_temps as $product_temp){
              $brand_id=ProductTempTool::getBrandIdByProdTempId($product_temp->product_temp_id);
              $brand_name='';
              if(!empty($brand_id)){
                  $brand_name=BrandToolService::getBrandNameByBrandId($brand_id);
              }
              $temp_name=$this->productTempTool->getProductTempNameByProductTempId($product_temp->product_temp_id);
              $arr=array(
                  "品牌"=>$brand_name,
                  "模板编号"=>$product_temp->product_temp_id,
                  "名称"=>$temp_name,
                  "颜色"=>$product_temp->colour_name,
                  "尺码"=>$product_temp->size_name,
                  "sku"=>$product_temp->sku,
                  "实际库存"=>$product_temp->actual_stock,
              );
              $rows[]=$arr;
          }
          $time=time();
          $path=date('Ym').DIRECTORY_SEPARATOR;
          $folder=public_path("purchase_order_excel".DIRECTORY_SEPARATOR.$path);
          @$this->mkFolder($folder);
          Excel::create($time, function($excel) use ($rows) {
              $excel->sheet('purchase_order', function($sheet) use ($rows) {
                  $sheet->fromArray($rows);
              });
          })->store('xls', $folder);
          $get_xls_url=asset('purchase_order_excel'.DIRECTORY_SEPARATOR.$path.DIRECTORY_SEPARATOR.$time.".xls");
         return $get_xls_url;
      }catch (\Exception $e){
          Log::info($e);
          return false;
      }
    }
    /**
     * 数据验证
     * @param Request $request
     * @param $check_data
     * @return mixed
     */
    public static function store(Request $request,$check_data)
    {
        $v = Validator::make($request->all(), $check_data);
        return $v;
    }
    /**
     * 创建文件夹
     * @param $path
     */
    function mkFolder($path)
    {
        try{
            if(!is_readable($path))
            {
                is_file($path) or mkdir($path,0777);
            }
        }catch (\Exception $e){
            Log::info('PrintService mkFolder 出现异常');
            Log::info($e);
            return false;
        }
    }
}